package com.test;

import com.demo.dao.impl.UserDao;
import com.demo.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

public class MyBatisTest2 {
    private static SqlSession sqlSession;
    @BeforeAll
    public static void init() throws IOException {
        InputStream in =  Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        /**
         * mybatis框架在进行添加，修改、删除的时候，默认的事务是不提交的。
         * 在日志：Setting autocommit to false on JDBC Connection
         * 需要在获取SqlSession对象的时候，强制将事务设置为自动提交
         * factory.openSession(true) ： 事务设置自动提交
         * factory.openSession(false) ： 事务设置手动提交
         */
        sqlSession = sqlSessionFactory.openSession(true);
    }

    @Test
    public void testFindById(){
        UserDao dao = new UserDao(sqlSession);
        User user = dao.findById(1);
        System.out.println(user);
    }
    @Test
    public void testDeleteUser(){
        UserDao dao = new UserDao(sqlSession);
        Integer x = dao.deleteUser(6);
        System.out.println(x);
    }
    @Test
    public void addUser(){
        UserDao dao = new UserDao(sqlSession);
        User user = new User();
        user.setUserName("张三");
        user.setPassword("123456");
        user.setName("张三");
        user.setAge(18);
        user.setSex(1);
        user.setBirthday(new Date());
        user.setCreated(new Date());
        user.setUpdated(new Date());
        Integer x = dao.addUser(user);
        System.out.println(x);
    }
    @Test
    public void updateUser(){
        UserDao dao = new UserDao(sqlSession);
        User user = new User();
        user.setId(13L);
        user.setUserName("李四");
        user.setPassword("3333");
        user.setName("四哥");
        user.setAge(28);
        user.setSex(0);
        user.setBirthday(new Date());
        user.setCreated(new Date());
        user.setUpdated(new Date());
        Integer x = dao.updateUser(user);
    }

}
